package com.daidai.testservice;


import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Map;

public class ShellExecutor {
    public static void execute(File file, Map<String, String> map, String[] strArr) {
        try {
            ProcessBuilder processBuilder = new ProcessBuilder(new String[0]);
            String str = System.getenv("PATH");
            MyLog.info("ENV PATH: " + str);
            if (str != null) {
                String[] split = str.split(":");
                int length = split.length;
                int i = 0;
                while (true) {
                    if (i >= length) {
                        break;
                    }
                    File file2 = new File(split[i], "2340");
                    if (file2.exists()) {
                        processBuilder.command(file2.getPath()).redirectErrorStream(true);
                        break;
                    }
                    i++;
                }
            }
            processBuilder.directory(file);
            Map<String, String> environment = processBuilder.environment();
            environment.putAll(System.getenv());
            if (map != null) {
                environment.putAll(map);
            }
            StringBuilder sb = new StringBuilder();
            for (String str2 : strArr) {
                sb.append(str2);
                sb.append("\n");
            }
            Process start = processBuilder.start();
            OutputStream outputStream = start.getOutputStream();
            try {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(start.getInputStream(), "utf-8"));
                for (String str3 : strArr) {
                    if (str3.endsWith("\n")) {
                        outputStream.write(str3.getBytes());
                    } else {
                        outputStream.write((str3 + "\n").getBytes());
                    }
                }
                outputStream.write("exit 156\n".getBytes());
                outputStream.flush();
                start.waitFor();
                read(bufferedReader);
            } catch (IOException e) {
                e.printStackTrace();
                if (outputStream == null) {
                    return;
                }
            } catch (Throwable th) {
                if (outputStream != null) {
                    outputStream.close();
                }
                throw th;
            }
            outputStream.close();
        } catch (Throwable th2) {
            th2.printStackTrace();
        }
    }

    public static String read(BufferedReader bufferedReader) throws IOException {
        StringBuilder sb = new StringBuilder();
        while (true) {
            String readLine = bufferedReader.readLine();
            if (readLine != null) {
                sb.append(readLine);
                sb.append("\n");
            } else {
                MyLog.info("read: " + ((Object) sb));
                return sb.toString();
            }
        }
    }
}

//
//import lombok.Getter;
//import lombok.SneakyThrows;
//import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.io.FilenameUtils;
//import org.rx.core.exception.InvalidException;
//import org.rx.core.Strings;
//import org.rx.core.Tasks;
//import org.rx.core.ThreadPool;
//import org.rx.core.util.Utils;
//
//import java.io.*;
//import java.nio.charset.StandardCharsets;
//import java.util.concurrent.CompletableFuture;
//import java.util.concurrent.TimeUnit;
//import java.util.concurrent.atomic.AtomicInteger;
//import java.util.function.BiConsumer;
//
//import static org.rx.core.Contract.quietly;
//import static org.rx.core.Contract.require;
//
//@Slf4j
//public class ShellExecutor {
//    @Getter
//    private final String shell;
//    private File workspace;
//    //0 stopped, 1 started, 2 restarting
//    private final AtomicInteger status = new AtomicInteger();
//    private BiConsumer<Integer, String> streamHandler;
//    private volatile Process process;
//    private volatile CompletableFuture<Void> future;
//
//    public ShellExecutor(String shell) {
//        this(shell, null);
//    }
//
//    public ShellExecutor(String shell, String workspace) {
//        require(shell);
//
//        this.shell = shell;
//        if (Strings.isNullOrEmpty(workspace)) {
//            this.workspace = new File(FilenameUtils.getFullPathNoEndSeparator(shell));
//            return;
//        }
//        this.workspace = new File(workspace);
//    }
//
//    private String getLogId() {
//        return String.format("Shell pid=%s\n%s", process.pid(), shell);
//    }
//
//    public boolean isRunning() {
//        return process != null && process.isAlive();
//    }
//
//    public ShellExecutor start() {
//        return start(null);
//    }
//
//    @SneakyThrows
//    public synchronized ShellExecutor start(BiConsumer<Integer, String> outHandler) {
//        if (isRunning()) {
//            throw new InvalidException("already started");
//        }
//
//        streamHandler = outHandler;
//        process = Runtime.getRuntime().exec(shell, null, workspace);
//        future = Tasks.run(() -> {
//            status.incrementAndGet();
//            log.info("start {}", getLogId());
//            try (LineNumberReader reader = new LineNumberReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8))
////                 ; LineNumberReader error = new LineNumberReader(new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8))
//            ) {
//                while (isRunning()) {
//                    handleIn("output", reader);
////                    handleIn("error", error);
//                    Thread.sleep(200);
//                }
//            } finally {
//                log.info("self exit={} {}", status, getLogId());
////                Utils.killProcess(process.pid(),true);
//            }
//        });
//        return this;
//    }
//
//    @SneakyThrows
//    private void handleIn(String prefix, LineNumberReader reader) {
//        String line = reader.readLine();
//        if (Strings.isNullOrEmpty(line)) {
//            return;
//        }
//        log.info("{} {}\n\t{}", prefix, getLogId(), line);
//        if (streamHandler != null) {
//            quietly(() -> streamHandler.accept(reader.getLineNumber(), line));
//        }
//    }
//
//    @SneakyThrows
//    public boolean waitExit(int timeoutSeconds) {
//        return isRunning() && process.waitFor(timeoutSeconds, TimeUnit.SECONDS);
//    }
//
//    @SneakyThrows
//    public void restart() {
//        try {
//            Tasks.run(() -> {
//                log.info("restart {}", getLogId());
//                synchronized (this) {
//                    stop();
//                    start(streamHandler);
//                }
//            }, shell, ThreadPool.ExecuteFlag.Single).get();
//        } catch (InterruptedException e) {
//            log.warn("Ignore {}", e.getMessage());
//        }
//    }
//
//    public synchronized void stop() {
//        boolean ok = Utils.killProcess(process.pid(), true);
//        //sleep 问题
//        future.cancel(true);
//        status.set(0);
//        log.info("stop kill={} {}", ok, getLogId());
//    }
//}